package com.sheepone.distributor;

import com.sheepone.distributor.event.EventContext;
import com.sheepone.distributor.util.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Miss.杨
 * @description
 * @since 2023-12-13 20:11
 */
public class Distributor {
    private static final Logger LOGGER = LoggerFactory.getLogger(Distributor.class);
    private final String name;
    private final List<DistributorLine> lines;
    public Distributor(String name,List<DistributorLine> lines){
        this.name = name;
        this.lines=lines;
    }
    public void distribute(String targetStation, String targetTopic, EventContext context){
        lines.get(NumberUtil.randomIndex(lines.size())).publish(targetStation,targetTopic,context);
    }

    public Distributor start(){
        lines.forEach(DistributorLine::start);
        LOGGER.info("【Distributor】 \"{}\" start to work",name);
        return this;
    }
    public void stop(){
        lines.forEach(DistributorLine::stop);
        WorkerStationManager.INSTANCE.stopAll();
        LOGGER.info("【Distributor】 \"{}\" has stopped",name);
    }

    public long hasPublishNum(){
        return lines.stream().mapToLong(DistributorLine::hasPublishNum).sum();
    }
}
